<?php

namespace app\api\model;

use app\common\service\Html;
use think\Db;

class TieBaComment extends \app\common\model\TieBaComment
{
    /**
     * 获取评论回复列表
     * @param $tieId
     * @param $page
     * @param $size
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getListByTie($tieId, $page, $size)
    {
        $offset = ($page - 1) * $size;
        $where = [
            'tie_id' => $tieId
        ];
        $model = static::field('id AS commentId, from_uid AS fromUid, from_nickname AS fromNickname,
        from_head_img AS fromHeadImg, to_nickname AS toNickname, content, create_time AS createTime, is_reply AS isReply')
            ->where($where)
            ->order(['create_time' => 'asc'])
            ->limit($offset, $size)
            ->select()
            ->toArray();
        foreach ($model as $key => $value) {
            $model[$key]['content'] = Html::encode($value['content']);
            $model[$key]['isReplyText'] = self::attributes('is_reply', $value['isReply']);
            $model[$key]['createTime'] = date('Y-m-d H:i:s', $value['createTime']);
            $model[$key]['fromPhone']  = self::selectUserPhone($value['fromUid']);
        }
        $count = static::where($where)->count();
        return [
            'list' => $model,
            'count' => $count
        ];
    }

    /**
     * 我的消息列表
     * @param $oauthId
     * @param $page
     * @param $size
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function myMessage($oauthId, $page, $size)
    {
        $offset = ($page - 1) * $size;
        // 有人评论我的帖子；（包括自己评论自己的帖子）
        // 有人回复我的评论；
        $sql = static::where(['tie_uid' => $oauthId])
            ->whereOr('to_uid', '=', $oauthId);

        $model = $sql->field('id AS commentId, tie_id AS tieId, from_uid AS fromUid, from_nickname AS fromNickname, 
        from_head_img AS fromHeadImg, to_nickname AS toNickname, content, create_time AS createTime, is_reply AS isReply, is_read')
            ->order(['create_time' => 'desc'])
            ->limit($offset, $size)
            ->select()
            ->toArray();
        foreach ($model as $key => $value) {
            $model[$key]['content'] = Html::encode($value['content']);
            $model[$key]['isReplyText'] = self::attributes('is_reply', $value['isReply']);
            $model[$key]['createTime'] = date('Y-m-d H:i:s', $value['createTime']);
            $model[$key]['fromPhone']  = self::selectUserPhone($value['fromUid']);
        }

        return [
            'list' => $model,
            'count' => $sql->count()
        ];
    }

    /**
     * 统计未读信息数量，大于99直接返回...
     * @param $oauthId
     * @return float|string
     */
    public static function unRead($oauthId)
    {
        $count = static::where(['is_read' => self::READ_NO])
            ->where(function ($query) use ($oauthId) {
                $query->where(['tie_uid' => $oauthId])
                    ->whereOr(['to_uid' => $oauthId]);
            })->count();
        return $count > 99 ? '...' : $count;
    }

    /**
     * 更新对应的评论|回复数据为已读状态
     * @param int $oauthId 登录的用户id
     * @param int $commentId 评论或者回复的id
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function updateRead($oauthId, $commentId)
    {
        $model = static::field('id, is_read')
            ->where(['id' => $commentId, 'is_read' => self::READ_NO])
            ->where(function ($query) use ($oauthId) {
                $query->where(['tie_uid' => $oauthId])->whereOr(['to_uid' => $oauthId]);
            })->find();
        if ($model) {
            $model->is_read = self::READ;
            $model->save();
        }
    }

    /**
     * 评论或者回复
     * @param $oauth
     * @param $tie
     * @param $content
     * @param $toUser
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function addOne($oauth, $tie, $content, $toUser)
    {
        $oauthId = $oauth['id'];

        static::create([
            'tie_id' => $tie['tieId'],
            'tie_uid' => $tie['uid'],
            'from_uid' => $oauthId,
            'from_nickname' => $oauth['nickname'],
            'from_head_img' => $oauth['head_img'],
            'to_uid' => $toUser ? $toUser['id'] : 0,
            'to_nickname' => $toUser ? $toUser['nickname'] : '',
            'content' => $content,
            'is_reply' => $toUser ? self::REPLY : self::REPLY_NO,
        ]);

        // 用户任意评论帖子一次，加积分
        $type = OauthIntegral::TYPE_COMMENT;
        $addNum = OauthIntegral::getNum($oauthId, $type);
        // 添加积分记录
        OauthIntegral::addOne($oauthId, $type, $addNum);
    }

    /**
     * 获取一条评论或者回复记录
     * @param $id
     * @return array|\PDOStatement|string|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getOne($id)
    {
        return static::field('id, from_uid AS fromUid')
            ->where(['id' => $id])
            ->find();
    }

    /**
     * 删除自己的评论或者回复
     * @param $id
     * @param $oauthId
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public static function deleteOne($id, $oauthId)
    {
        static::where([
            'id' => $id,
            'from_uid' => $oauthId
        ])->delete();
    }
    
    
    /**
     * 未读消息
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function unReadMessage($data)
    {
        
        $where['tie_uid']  = $data['uid'];
        $where['is_read']  = 0;
        $where['from_uid'] =  array('neq',$data['uid']);
        //$model =  static::where($where)->count('id');
        $model =  static::where("tie_uid = ${data['uid']} and is_read = 0 and from_uid != ${data['uid']}")->count('id');
        
        //print_r(static::getLastsql());
        return [
            'count' => $model
        ];
    }
    
    /**
     * 查询用户的phone
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function selectUserPhone($uid)
    {
        $data = DB::table('oauth')->field('phone')
        ->where(['id' => $uid])
        ->find();
        return $data['phone']?$data['phone']:null;
    }
}